package com.ssm.oss.adapter;

import com.ssm.oss.util.MinioUtil;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.http.Method;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * Minio相关操作的具体逻辑
 */
@Log4j2
public class MinioStorageAdapter implements StorageAdapter {

    @Resource
    private MinioUtil minioUtil;

    @Value("${minio.url}")
    private String url;

    @Override
    @SneakyThrows //Lombok中的注解 会在编译期补上异常处理
    public void createBucket(String bucket) {
        minioUtil.createBucket(bucket);
    }

    /**
     * 上传文件
     * @param multipartFile
     * @param bucket
     * @param objectName 为空，文件路径为根目录；不为空，文件路径为objectName目录下
     */
    @Override
    @SneakyThrows
    public void uploadFile(MultipartFile multipartFile, String bucket, String objectName) {
        minioUtil.createBucket(bucket);
        if(objectName != null) {
            minioUtil.uploadFile(multipartFile.getInputStream(), bucket, objectName + "/" + multipartFile.getOriginalFilename());
        } else {
            minioUtil.uploadFile(multipartFile.getInputStream(), bucket, multipartFile.getOriginalFilename());
        }
    }

    /**
     * 获取文件在oss中的url
     * @param bucket
     * @param objectName
     * @return
     */
    @Override
    public String getUrl(String bucket, String objectName) {
        return url + "/" + bucket + "/" + objectName;
    }


}
